local _, ADDONSELF = ...

local qrcode = ADDONSELF.qrcode

local BLOCK_SIZE = 5

local function CreateQRTip(qrsize)
    local f = CreateFrame("Frame", nil, UIParent)

    local function CreateBlock(idx)
        local t = CreateFrame("Frame", nil, f)

        t:SetWidth(BLOCK_SIZE)
        t:SetHeight(BLOCK_SIZE)
        t.texture = t:CreateTexture(nil, "OVERLAY")
        t.texture:SetAllPoints(t)

        local x = (idx % qrsize) * BLOCK_SIZE
        local y = (math.floor(idx / qrsize)) * BLOCK_SIZE

        t:SetPoint("TOPLEFT", f, 20 + x, -20 - y);

        return t
    end

    do
        f:SetFrameStrata("BACKGROUND")
        f:SetWidth(qrsize * BLOCK_SIZE + 40)
        f:SetHeight(qrsize * BLOCK_SIZE + 40)
        f:SetMovable(true)
        f:EnableMouse(true)
        -- f:SetBackdrop({ 
        --    bgFile = "Interface/Tooltips/UI-Tooltip-Background",
        --    edgeFile = "Interface/Tooltips/UI-Tooltip-Border",
        --    tile = true,
        --    tileEdge = true,
        --    tileSize = 16,
        --    edgeSize = 16,
        --    insets = { left = 4, right = 4, top = 4, bottom = 4 },    
        -- })

        -- f:SetBackdropColor(0, 0, 0);

        f:SetPoint("CENTER", 0, 0)
        f:RegisterForDrag("LeftButton")
        f:SetScript("OnDragStart", function(self) self:StartMoving() end)
        f:SetScript("OnDragStop", function(self)
            self:StopMovingOrSizing()
        end)
    end

    do
        local b = CreateFrame("Button", nil, f, "UIPanelCloseButton")
        b:SetPoint("TOPRIGHT", f, 0, 0);
    end

    f.boxes = {}

    f.SetBlack = function(idx) f.boxes[idx].texture:SetColorTexture(0, 0, 0) end

    f.SetWhite = function(idx) f.boxes[idx].texture:SetColorTexture(1, 1, 1) end

    for i = 1, qrsize * qrsize do tinsert(f.boxes, CreateBlock(i - 1)) end

    return f
end

local function C_ContributionCollector1()
    -- 只展示激活
    local returnString = ""
    local item = ""
    local sqltmp = ""
    local contriTmp = ""
    local now = ""
    local camp = ""
    local stateAmounttemp = ""
    local stime = 0
    local endtime = 0
    local sql = ""
    local contri = ""
    for contributionID = 5, 120 do
        local n, d = C_ContributionCollector.GetName(contributionID),
                     C_ContributionCollector.GetDescription(contributionID)
        local state, stateAmount, timeOfNextStateChange, startTime =
            C_ContributionCollector.GetState(contributionID);
        -- local appearanceData = C_ContributionCollector.GetContributionAppearance(contributionID, state);
        -- if state == 1 or state == 2 then        
        if n ~= "" then
            if state == 1 or state == 2 then
                -- print (n)
                -- print (contributionID)
                local updateTime = GetServerTime()
                if contributionID == 11 or contributionID == 118 then
                    camp = "部落"
                elseif contributionID == 116 or contributionID == 117 then
                    camp = "联盟"
                end

                if state == 1 then -- 建造
                    if stateAmount < 1 or stateAmount > 0.01 then
                        stateAmounttemp = math.floor(stateAmount * 100)
                    end
                    if startTime then
                        local startTime1 = GetServerTime() - startTime
                        local timeDiff = startTime1 / stateAmounttemp * 100
                        local totaltime =
                            SecondsToTime(timeDiff, false, true, 2)
                        local timeremaining =
                            SecondsToTime(
                                startTime1 / stateAmounttemp *
                                    math.floor((1 - stateAmount) * 100), false,
                                true, 2)
                        stime = startTime;
                        endtime = startTime + timeDiff
                        -- item = "NO."..contributionID .."\n建造"..n.."\n进度"..stateAmounttemp.."\n总时间"..totaltime.."\n剩余时间"..timeremaining.."\n开始时间"..date("%Y-%m-%d %H:%M:%S",startTime).."\n结束时间"..date("%Y-%m-%d %H:%M:%S",endtime).."\n"
                    end
                    -- sqltmp = "UPDATE contriData SET contributionID = "..contributionID..",state = "..state..",camp = '"..camp.."',startTime = "..stime..",endtime = ".. math.floor(endtime)..",updateTime = "..updateTime.." WHERE name = '"..n.."';"

                elseif state == 2 then -- 激活
                    now = timeOfNextStateChange - GetServerTime();
                    stime = timeOfNextStateChange - 604800;
                    now = SecondsToTime(now, false, true, 2)
                    item = "NO." .. contributionID .. "\n激活\n" .. n ..
                               "\n剩余时间" .. now .. "\n开始时间" ..
                               date("%Y-%m-%d %H:%M:%S", stime) .. "\n"
                    endtime = timeOfNextStateChange

                elseif state == 0 then -- 没有
                    -- item = "NO."..contributionID .."\n没有\n"..n.."\n"
                elseif state == 3 then -- 遭到攻击
                    -- item = "NO."..contributionID .."\n遭到攻击\n"..n.."\n"
                elseif state == 4 then -- 被毁
                    -- item = "NO."..contributionID .."\n被毁\n"..n.."\n"
                end
                sqltmp = "UPDATE contriData SET contributionID = " ..
                             contributionID .. ",state = " .. state ..
                             ",camp = '" .. camp .. "',startTime = " .. stime ..
                             ",endtime = " .. math.floor(endtime) ..
                             ",updateTime = " .. updateTime .. " WHERE name = '" ..
                             n .. "';"
                -- contriTmp = '{"id":1,"contributionID":'..contributionID..',"icon": "https://www.fateplayer.com/api-wow/contriData/jiliubao.jpg","name": "'..n..'","camp": "'..camp..'","state": '..state..',"starttime": '..starttime..',"endtime": '..endtime..',"updatetime": '..updatetime..'},'
                contriTmp = '{"id":1,"contributionID":' .. contributionID ..
                                ',"icon": "https://www.fateplayer.com/api-wow/contriData/jiliubao.jpg","name": "' ..
                                n .. '","camp": "' .. camp .. '","state": ' ..
                                state .. ',"starttime": ' .. stime ..
                                ',"endtime": ' .. math.floor(endtime) ..
                                ',"updatetime": ' .. updateTime .. '},'
                -- contriArray[contributionID]= {
                --					["contributionID"] = contributionID,
                --					["state"] = state,
                --					["name"] = n,
                --					--["remainingTime"] = now,
                --					["startTime"] = stime,
                --					["camp"] = camp,
                --					["contributionID"] = contributionID,
                --					["updateTime"] = updateTime,
                --					["endtime"] = endtime,
                --					["sql"] = sqltmp
                --				}
                sql = sql .. sqltmp
                contri = contri .. contriTmp
                returnString = returnString .. item .. camp .. '\n'
            end
        end
        -- end
    end
    -- print ('复制尖括号里内容导入到小程序|cffffe00a<|r|cffff7d0a['..sql..']|r|cffffe00a>|r')
    -- print (returnString)
    return sql

end

SlashCmdList["ML"] = function(msg, editbox)
    local sql = C_ContributionCollector1()
    local ok, tab_or_message = qrcode(sql, 4)
    if not ok then
        print(tab_or_message)
    else
        local tab = tab_or_message
        local size = #tab

        local f = CreateQRTip(size)
        f:Show()

        for x = 1, #tab do
            for y = 1, #tab do

                if tab[x][y] > 0 then
                    f.SetBlack((y - 1) * size + x - 1 + 1)
                else
                    f.SetWhite((y - 1) * size + x - 1 + 1)
                end
            end
        end
    end

end
SLASH_ML1 = "/ML"

